package com.theatre.userservice.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.theatre.userservice.annotation.RequirePermission;
import com.theatre.userservice.Controller.contxet.BaseContext;
import com.theatre.userservice.mapper.ShopMapper;
import com.theatre.userservice.model.dto.ShopDTO;
import com.theatre.userservice.model.entity.Publisher;
import com.theatre.userservice.model.entity.Shop;
import com.theatre.userservice.model.vo.PublisherVO;
import com.theatre.userservice.model.vo.Result;
import com.theatre.userservice.model.vo.ScriptVO;
import com.theatre.userservice.model.vo.ShopVO;
import com.theatre.userservice.model.vo.utils.FileUploadUtil;
import com.theatre.userservice.service.ShopService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/shop")
@Tag(name = "店铺接口", description = "提供店铺相关的接口")
public class ShopController {

    @Autowired
    ShopMapper shopMapper;

    @Autowired
    ShopService shopService;

    @Value("${upload.base-dir}")
    private String uploadBaseDir;




    // 注册成为店铺，要求角色为商家
    @RequirePermission("content:manage")
    @PostMapping("/insert")
    @Operation(summary = "新增店铺", description = "新增店铺")
    public Result<Long> insert(@RequestBody ShopDTO shopDTO) {
        // 校验参数（删除超级管理员）
        Long currentUserId = BaseContext.getUserId();
        if (currentUserId == null || currentUserId == 2 || currentUserId == 4) {
            return Result.error("商家才有资格注册店铺");
        }

        // 参数校验（可以根据实际需求添加更详细的校验逻辑）
        if (shopDTO.getName() == null || shopDTO.getName().isEmpty()) {
            return Result.error("店铺名称不能为空");
        }
        if (shopDTO.getAddress() == null || shopDTO.getAddress().isEmpty()) {
            return Result.error("店铺地址不能为空");
        }
        if (shopDTO.getPhone() == null || shopDTO.getPhone().isEmpty()) {
            return Result.error("联系电话不能为空");
        }
        Shop shop = shopDTO.toEntity();
        shop.setUserId(currentUserId);
        shop.setStatus(0); // 待审核状态
        // 保存到数据库
        int insertResult = shopMapper.insert(shop);
        if (insertResult <= 0) {
            return Result.error("新增店铺失败");
        }
        return Result.success(shop.getId());
    }

    // 上传营业执照，要求角色为商家
    @RequirePermission("content:manage")
    @PostMapping("/uploadLicense")
    @Operation(summary = "上传营业执照", description = "上传营业执照")
    public Result<String> uploadLicense(@RequestParam("file") MultipartFile file) {
        Long currentUserId = BaseContext.getUserId();

        if (currentUserId == null || currentUserId == 2 || currentUserId == 4) {
            return Result.error("商家才有资格上传营业执照");
        }

        if (file == null || file.isEmpty()) {
            return Result.error("请上传营业执照文件");
        }

        try {
            String relativePath = FileUploadUtil.saveFile(file, uploadBaseDir, "licenses");

            Shop shop = new Shop();
            shop.setUserId(currentUserId);
            shop.setLicenseFile(relativePath);

            int updated = shopMapper.update(shop,
                    new LambdaUpdateWrapper<Shop>().eq(Shop::getUserId, currentUserId));

            if (updated <= 0) {
                return Result.error("更新营业执照失败");
            }

            return Result.success(relativePath);
        } catch (Exception e) {
            throw new RuntimeException("上传营业执照失败", e);
        }
    }

    //显示已购买的剧本和他的发行商的信息
    @GetMapping("/{id}/purchased")
    @Operation(summary = "显示已购买的剧本", description = "根据商户id显示已购买的剧本和它的发行商的信息")
    public Result<List<ScriptVO>> showPurchased(@PathVariable("id") Long id) {
        if (shopMapper.selectById(id).getStatus() != 1) {
            return Result.error("商户未通过审核");
        }
        Long currentUserId = BaseContext.getUserId();
        if (currentUserId == null || currentUserId == 2 || currentUserId == 4) {
            return Result.error("商家才有资格查看购买信息");
        }
        // 查询已购买的剧本
        List<ScriptVO> scriptVO = shopService.selectPurchased(id);
        // 查询发行商信息
        return Result.success(scriptVO);
    }
    @GetMapping("/{id}")
    @Operation(summary = "显示商户信息", description = "根据商户id显示商户信息")
    public Result<ShopVO> showShop(@PathVariable("id") Long id) {
        Long currentUserId = BaseContext.getUserId();
        if (currentUserId == null || currentUserId == 2 || currentUserId == 4) {
            return Result.error("商家才有资格查看商户信息");
        }
        // 查询商户信息
        Shop shop = shopMapper.selectById(id);
        ShopVO shopVO = new ShopVO();
        BeanUtils.copyProperties(shop, shopVO);
        return Result.success(shopVO);
    }
    //更改商户信息
    @RequirePermission("content:manage")
    @PutMapping("/{id}")
    @Operation(summary = "更改商户信息", description = "根据商户id更改商户信息")
    public Result<String> updateShop(@PathVariable("id") Long id, @RequestBody ShopDTO shopDTO) {
        Long currentUserId = BaseContext.getUserId();
        if (currentUserId == null || currentUserId == 2 || currentUserId == 4) {
            return Result.error("商家才有资格更改商户信息");
        }
        // 参数校验
        if (shopDTO.getName() == null || shopDTO.getName().isEmpty()) {
            return Result.error("店铺名称不能为空");
        }
        if (shopDTO.getAddress() == null || shopDTO.getAddress().isEmpty()) {
            return Result.error("店铺地址不能为空");
        }
        if (shopDTO.getPhone() == null || shopDTO.getPhone().isEmpty()) {
            return Result.error("联系电话不能为空");
        }
        // 更新数据库
        Shop shop = shopDTO.toEntity();
        shop.setId(id);
        int updateResult = shopMapper.updateById(shop);
        if (updateResult <= 0) {
            return Result.error("更新失败");
        }
        return Result.success("更新成功");
    }
    @GetMapping("/user")
    @RequirePermission("content:manage")
    @Operation(summary = "根据用户ID查询店铺", description = "根据当前登录用户的ID查询所属店铺信息")
    public Result<ShopVO> getShopByUserId() {
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null || currentId == 2 || currentId == 4) {
            return Result.error("没有资格查看店铺信息");
        }
        Long currentUserId = BaseContext.getUserId();
        Shop shop = shopMapper.selectOne(
                new QueryWrapper<Shop>().eq("user_id", currentUserId)
        );
        if (shop == null) {
            return Result.error("未找到对应的商铺信息,请先注册门店");
        }

        ShopVO shopVO = new ShopVO();
        BeanUtils.copyProperties(shop, shopVO);
        return Result.success(shopVO);
    }
}
